/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

// PostCSS plugins
const cssnext = require('postcss-cssnext');
const postcssFocus = require('postcss-focus');
const postcssReporter = require('postcss-reporter');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    rules: [
    {
      test: /\.(js|jsx)$/, 
      exclude: /node_modules/, 
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [
            "es2015",
            "react",
            "stage-0"
          ],
        }
      }]
    }, 
    {
      test: /\.css$/,
      use: options.cssLoaders,
    }, {
      test: /\.less$/,
      use: [
        'style-loader',
        {
          loader: 'css-loader',
          query: {
            importLoader: 1,
            localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
            modules: true,
          }
        },
        'postcss-loader',
        'less-loader'
      ]
    }, {
      test: /\.html$/,
      use: ['html-loader']
    }],
  },
  plugins: options.plugins.concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
    new ProgressBarPlugin(), 
    new CopyWebpackPlugin([
        { from: path.resolve(process.cwd(), 'vendor'), to: 'vendor' },
        { from: path.resolve(process.cwd(), 'app/assets'), to: 'assets'}
    ])
  ]),
  resolve: {
    modules: ["app", "node_modules"],
    aliasFields: ["main"],
    descriptionFiles: ["package.json"],
    mainFields: ['main', 'browser', 'module'],
    extensions: [".js", ".jsx"],
    alias: {
      antd: 'antd/dist/antd.min.js',
    },
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  stats: true, // Don't show stats in the console
});
